package com.hc.controller;

import com.hc.bean.Result;
import com.hc.bean.ResultUtil;
import com.hc.jwt.JwtConst;
import com.hc.jwt.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @PostMapping(value = "/login")
    public Result userLogin(@RequestParam(name = "username", required = true) String username,
                            @RequestParam(name = "password", required = true) String password,
                            HttpServletResponse response) {
        // 获取当前用户主体
        Subject subject = SecurityUtils.getSubject();
        String msg = null;
        boolean loginSuccess = false;
        // 将用户名和密码封装成 UsernamePasswordToken 对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            msg = "登录成功！";
            loginSuccess = true;
        } catch (UnknownAccountException uae) { // 账号不存在
            msg = "用户名与密码不匹配，请检查后重新输入！";
        } catch (IncorrectCredentialsException ice) { // 账号与密码不匹配
            msg = "用户名与密码不匹配，请检查后重新输入！";
        } catch (LockedAccountException lae) { // 账号已被锁定
            msg = "该账户已被锁定，如需解锁请联系管理员！";
        } catch (AuthenticationException ae) { // 其他身份验证异常
            msg = "登录异常，请联系管理员！";
        }
        Result res = new Result();
        if (loginSuccess) {
            // 若登录成功，签发 JWT token
            String jwtToken = JwtUtil.createToken(username, JwtConst.SECRET);
            // 将签发的 JWT token 设置到 HttpServletResponse 的 Header 中
            System.out.println("jwtToken:  " + jwtToken);
            response.setHeader(JwtConst.AUTH_HEADER, jwtToken);
            //
            res.setCode(200);
        } else {
            res.setCode(401);
        }
        res.setMsg(msg);
        return res;
    }

    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        //在这里执行退出系统前需要清空的数据
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()) {
            subject.logout();
        }
        System.out.println("退出登录成功");
        return ResultUtil.success("退出登录");
    }

}
